/*
 *  Copyright (c) 2011 The pim project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "cpu_info.h"

#if defined(_WIN32)
#include <Windows.h>
#elif defined(CCORE_MAC)
#include <sys/sysctl.h>
#include <sys/types.h>
#else  // defined(CCORE_LINUX) or defined(CCORE_ANDROID)
#include <unistd.h>
#endif
#include <stdint.h>

namespace qb {
unsigned int CpuInfo::number_of_cores_ = 0;

unsigned int CpuInfo::DetectNumberOfCores() {
  if (!number_of_cores_) {
#if defined(_WIN32)
    SYSTEM_INFO si;
    GetSystemInfo(&si);
    number_of_cores_ = static_cast<unsigned int>(si.dwNumberOfProcessors);

#elif defined(CCORE_LINUX) || defined(CCORE_ANDROID)
    number_of_cores_ = static_cast<uint32_t>(sysconf(_SC_NPROCESSORS_ONLN));

#elif defined(CCORE_MAC)
    int name[] = {CTL_HW, HW_AVAILCPU};
    int ncpu;
    size_t size = sizeof(ncpu);
    if (0 == sysctl(name, 2, &ncpu, &size, NULL, 0)) {
      number_of_cores_ = static_cast<uint32_t>(ncpu);

    } else {
      number_of_cores_ = 1;
    }
#else

    number_of_cores_ = 1;
#endif
  }
  return number_of_cores_;
}
}  // namespace qb
